<template>
  <!-- 筛选区 -->
  <div class="sub-filter">
    <div class="item" v-for="item in list" :key="item.id">
      <div class="head">{{ item.name }}：</div>
      <div class="body">
        <a href="javascript:;" @click="setfilterList(item, {})"
        :class="{active:item.activeName === undefined}">全部</a>
        <a
          href="javascript:;"
          v-for="p in item.properties"
          :key="p.id"
          @click="setfilterList(item, p)"
          :class="{active:item.activeName === p.name}"
        >
          {{ p.name }}
        </a>
      </div>
    </div>
  </div>
</template>

<script>
import { inject, computed, reactive } from 'vue'
export default {
  name: 'SubFilter',
  setup () {
    const subFilter = inject('subFilter')
    // 获取父组件发请求所需的数据
    const reqParams = inject('reqParams')
    // console.log(subFilter.value)
    // 计算属性随时监听变化
    const list = computed(() => {
      return [
        // 品牌数据
        reactive({
          id: 'brand',
          name: '品牌',
          properties: subFilter.value.brands
        }),
        // 规格数据
        ...subFilter.value.saleProperties
      ]
    })

    // 数据筛选
    const setfilterList = (theItem, theItem2) => {
      console.log(list)
      const groupName = theItem.name // 属性组名称
      const propertyName = theItem2.name // 属性名称
      // 👍 给一级对象添加收集到的数据，用于筛选区高亮
      theItem.activeName = propertyName
      // console.log(theItem, propertyName)

      // 品牌筛选
      if (groupName === '品牌') {
        reqParams.brandId = theItem2.id
        return
      }

      const attr = { groupName, propertyName }
      // 如果存在相同属性组 就替换
      const obj = reqParams.attrs.find((item) => item.groupName === groupName)
      if (obj) {
        // 替换
        obj.propertyName = propertyName
      } else {
        // 新增
        reqParams.attrs.push(attr)
      }
    }

    return { list, setfilterList }
  }
}
</script>

<style scoped lang='less'>
// 筛选区
.sub-filter {
  background: #fff;
  padding: 25px;
  .item {
    display: flex;
    line-height: 40px;
    .head {
      width: 80px;
      color: #999;
    }
    .body {
      flex: 1;
      a {
        margin-right: 36px;
        transition: all 0.3s;
        display: inline-block;
        &.active,
        &:hover {
          color: @xtxColor;
        }
      }
    }
  }
}
</style>
